/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.box.storage.indexed.impl

import cool.taomu.box.storage.indexed.abs.AbsIndexed
import cool.taomu.box.storage.indexed.rhino.JsRhinoScript
import java.util.Objects
import java.util.concurrent.ConcurrentSkipListMap
import java.util.concurrent.atomic.AtomicLong
import org.eclipse.xtend.lib.annotations.ToString

@ToString
class Indexed extends AbsIndexed {
	val static storage = new ConcurrentSkipListMap<String, ConcurrentSkipListMap<String, String>>();
	val static keyPathMap = new ConcurrentSkipListMap<String, String>();
	var index = new AtomicLong(0);
	var String name;

	override open(String name) {
		this.name = name;
		if(!storage.containsKey(this.name)){
			storage.put(this.name, new ConcurrentSkipListMap<String, String>());
		}
	}

	override open(String name, String version) {
		this.open(#[name, version].join("@"));
	}

	override createKeyPath(String id) {
		Objects.requireNonNull(this.name);
		keyPathMap.put(this.name, id);
	}

	override createIndex(String fieldName, boolean unique) {
		throw new UnsupportedOperationException("TODO: auto-generated method stub")
	}

	override get(String key) {
		Objects.requireNonNull(this.name);
		storage.get(this.name).get(key);
	}

	override put(String result) {
		Objects.requireNonNull(this.name);
		var String keyPath;
		if (keyPathMap.containsKey(this.name)) {
			keyPath = this.getKeyPath(keyPathMap.get(this.name), result) as String;
		} else {
			keyPath = String.valueOf(index.incrementAndGet);
		}
		storage.get(this.name).put(keyPath as String, result);
	}

	override remove(String key) {
		Objects.requireNonNull(this.name);
		storage.get(this.name).remove(key)
	}

	override clear() {
		Objects.requireNonNull(this.name);
		storage.get(this.name).clear();
	}

	def static void main(String[] args) {
		var im = new Indexed();
		im.open("aa");
		im.createKeyPath("id");
		im.put("{\"id\":\"aa\",\"name\":\"Hello World\"}");
		println(im.get("aa"))
		var im1 = new Indexed();
		im1.open("aa");
		println(im1.get("aa"))
	}

}
